#ifndef __WEBSOCKET_HANDLER__
#define __WEBSOCKET_HANDLER__


#include <winsock2.h>
#include <iostream>
#include <map>
#include <sstream>
#include "base64.h"
#include "sha1.h"
#include "debug_log.h"
#include "json/json.h"
#include "websocket_request.h"
#include "websocket_respond.h"

#include "SoundManager.h"

#define MAGIC_KEY "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

enum WEBSOCKET_STATUS {
	WEBSOCKET_UNCONNECT = 0,
	WEBSOCKET_HANDSHARKED = 1,
};

typedef std::map<std::string, std::string> HEADER_MAP;
class UDPApiCall :public UDPApi{
public:
	virtual void sendPttTcpInfo(char *buff){
		if (fd_ <= 0 || fd_ > 0xFFFF)
			return;
		DEBUG_LOG("send rsp fd_=%d len=%d buf:%s", fd_, strlen(buff), buff);

		char t_buf[1024];
		memset(t_buf, 0, sizeof t_buf);
		t_buf[0] = 0xFF & 0x81;
		t_buf[1] = 0x7F & strlen(buff);
		memcpy(t_buf + 2, buff, strlen(buff));
		//int len=response_->build_websocket_msg(buff, strlen(buff));
		send(fd_, (char *)t_buf, strlen(buff) + 2, 0);
		return;
	}
	void setFd(int fd){ fd_ = fd; }
	virtual void setPttUid(unsigned int id){
		pttCurUid = id;
	}
public:
	int fd_;
	unsigned int pttCurUid;
};
extern UDPApiCall gUdpApi;
class Websocket_Handler{
public:
	Websocket_Handler(int fd);
	~Websocket_Handler();
	int process();
	int endprocess();
	inline char *getbuff();
private:
	int handshark();
	void parse_str(char *request);
	int fetch_http_info();
	int send_data(char *buff);
	int parseStartPtt(Json::Value &value);
	int parseStopPtt(Json::Value &value);
	int parseCtlPtt(Json::Value &value);
	int send_rsp_data(char *buff);
private:
	char buff_[2048];
	WEBSOCKET_STATUS status_;
	HEADER_MAP header_map_;
	int fd_;
	Websocket_Request *request_;
	Websocket_Respond *response_;
};

inline char *Websocket_Handler::getbuff(){
	return buff_;
}

#endif
